import React from "react";
import store, { RootState } from "../../store";
import { connect } from "react-redux";
interface StateType {
  count: number;
}

interface PropsType {
  message: string;
}

type Props = PropsType &
  ReturnType<typeof mapStateToProps> &
  ReturnType<typeof mapDispatchToProps>;

class Index extends React.Component<Props, StateType> {
  timer: NodeJS.Timer | null = null;
  h1: React.RefObject<HTMLHeadingElement>;
  constructor(props: any) {
    super(props);
    this.state = {
      count: 1,
    };

    this.h1 = React.createRef();
  }

  addCount() {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  }
  render(): React.ReactNode {
    const { count } = this.state;
    const { message, name, age, sex, edit } = this.props;

    return (
      <div>
        {name}-{sex}- {age}
        <button onClick={() => edit("李四")}>修改名字</button>
        <hr />
        <h1 ref={this.h1}>{message}</h1>
        <h1>{count}</h1>
        <button onClick={() => this.setState({ count: count + 1 })}>+1</button>
        <button onClick={() => this.addCount()}>+1</button>
      </div>
    );
  }

  click = () => {
    console.log(1231231231);
  };
  componentDidMount() {
    console.log("页面准备就绪了");
    this.timer = setInterval(() => {
      console.log(1);
    }, 1000);
    console.log(this.h1.current);

    document.addEventListener("click", this.click);
  }
  shouldComponentUpdate(nextProps: PropsType, nextState: StateType) {
    // 性能优化
    // this.props;
    // this.state;
    return true;
  }
  componentDidUpdate(prevProps: PropsType, prevState: StateType) {
    // this.props;
    // this.state;
    console.log("有数据更新了");
  }
  componentWillUnmount() {
    console.log("被销户了");
    console.log(this.timer);
    clearInterval(this.timer as NodeJS.Timer);
    document.removeEventListener("click", this.click);
  }
}

const mapStateToProps = (state: RootState) => {
  return {
    name: state.user.name,
    age: state.user.age,
    sex: state.user.sex,
  };
};

const mapDispatchToProps = (dispatch: any) => {
  return {
    edit(name: string) {
      dispatch({ type: "editName", payload: name });
    },
  };
};

export const TestClassComp =  connect(mapStateToProps, mapDispatchToProps)(Index);
